package com.bjsxt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjsxt.constants.Constants;
import com.bjsxt.domain.DictData;
import com.bjsxt.dto.DictTypeDto;
import com.bjsxt.mapper.DictDataMapper;
import com.bjsxt.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.bjsxt.mapper.DictTypeMapper;
import com.bjsxt.domain.DictType;
import com.bjsxt.service.DictTypeService;

import java.util.Arrays;
import java.util.List;

@Service
public class DictTypeServiceImpl implements DictTypeService{

    @Autowired
    private DictTypeMapper dictTypeMapper;

    @Autowired
    private DictDataMapper dictDataMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 分页查询字典类型 可以根据条件进行筛选
     * @param dictTypeDto
     * @return
     */
    @Override
    public DataGridView listPage(DictTypeDto dictTypeDto) {
        // 条件构造器
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        // 字典类型名称模糊查询
        qw.like(StringUtils.isNoneBlank(dictTypeDto.getDictName()),DictType.COL_DICT_NAME, dictTypeDto.getDictName());
        // 字典类型的类型模糊查询
        qw.like(StringUtils.isNotBlank(dictTypeDto.getDictType()),DictType.COL_DICT_TYPE, dictTypeDto.getDictType());
        // 字典状态查询
        qw.eq(StringUtils.isNotBlank(dictTypeDto.getStatus()),DictType.COL_STATUS, dictTypeDto.getStatus());
        // 字典开始与结束时间查询
        // 创建时间大于等于开始时间 小于等于结束时间
        qw.ge(null!= dictTypeDto.getBeginTime(),DictType.COL_CREATE_TIME, dictTypeDto.getBeginTime());
        qw.le(null!= dictTypeDto.getEndTime(),DictType.COL_CREATE_TIME, dictTypeDto.getEndTime());

        // 构建分页条件
        Page<DictType> page = new Page<>(dictTypeDto.getPageNum(),dictTypeDto.getPageSize());

        // 开始查询
        dictTypeMapper.selectPage(page,qw);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 查询所有可用的字典类型
     * @return
     */
    @Override
    public DataGridView list() {
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        return new DataGridView(null,dictTypeMapper.selectList(qw));
    }

    /**
     * 根据id和字典类型名判断类型是否存在
     * @param dictId 字典主键
     * @param dictType 字典类型
     * @return
     */
    @Override
    public Boolean checkDictTypeUnique(Long dictId, String dictType) {
        dictId = (dictId==null)?-1L:dictId;
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_DICT_TYPE,dictType);
        DictType sysDictType = dictTypeMapper.selectOne(qw);
        if (null!=sysDictType){
            // 说明存在
            return true;
        }
        // 不存在
        return false;
    }

    /**
     * 增加
     * @param dictTypeDto
     * @return
     */
    @Override
    public int insert(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dictTypeDto,dictType);
        dictType.setCreateTime(DateUtil.date());
        dictType.setCreateBy(dictTypeDto.getSimpleUser().getUserName());
        return this.dictTypeMapper.insert(dictType);
    }

    @Override
    public int update(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dictTypeDto,dictType);
        dictType.setUpdateBy(dictTypeDto.getSimpleUser().getUserName());
        return dictTypeMapper.updateById(dictType);
    }

    @Override
    public int deleteDictTypeByIds(Long[] dictIds) {
        List<Long> ids = Arrays.asList(dictIds);
        if (null!=ids&&ids.size()>0){
            return dictTypeMapper.deleteBatchIds(ids);
        }else {
            return -1;
        }
    }

    @Override
    public DictType selectDictTypeById(Long dictId) {
        return dictTypeMapper.selectById(dictId);
    }

    /**
     * 同步数据到redis中分析
     * 1.查询出所有可用的字典类型
     * 2.根据字典类型查询字典数据
     * 3.把字典数据转换为json字符串 存到redis
     * 设计key
     * dict:dictType
     * 如:dict:sys_user_sex--->[{},{}]
     */
    @Override
    public void dictCacheAsync() {
        //查询出所有可用的字典类型
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_STATUS,Constants.STATUS_TRUE);
        List<DictType> dictTypeList = dictTypeMapper.selectList(qw);
        for (DictType dictType : dictTypeList) {
            //根据字典类型查询出字典数据
            QueryWrapper<DictData> qwd = new QueryWrapper<>();
            qwd.eq(DictData.COL_STATUS,Constants.STATUS_TRUE);
            qwd.eq(DictData.COL_DICT_TYPE,dictType.getDictType());
            qwd.orderByAsc(DictData.COL_DICT_SORT);
            List<DictData> dictDataList = dictDataMapper.selectList(qwd);
            String json = JSON.toJSONString(dictDataList);
            // 存入redis
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set(Constants.DICT_REDIS_PROFIX+dictType.getDictType(),json);
        }
    }
}
